package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.common.enums.dict.HouseCategory;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.yipaiju.domain.Favorite;
import com.ruoyi.yipaiju.service.IFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/favorites")
public class FavoritesController extends BaseController {

    @Autowired
    private IFavoriteService favoriteService;

    /**
     * 添加收藏
     * @param favorite
     * @return
     */
    @PostMapping("")
    public ApiResult add(@RequestBody Favorite favorite) {
        favorite.setClient(SecurityUtils.getUserId().toString());
        if (favorite.getForeclosedHouseId() != null){
            favorite.setFavoriteType(HouseCategory.FORECLOSED.getValue());
        }
        if (favorite.getDiscountHouseId() != null){
            favorite.setFavoriteType(HouseCategory.DISCOUNT.getValue());
        }
        favoriteService.insertFavorite(favorite);
        return ApiResult.success(favorite);
    }

    /**
     * 删除收藏
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public TableDataApi remove(@PathVariable Long id)
    {
        favoriteService.deleteFavoriteById(id);
        startPageApi();
        List<Favorite> favorites = favoriteService.selectFavoritesHouseInfo(Builder.of(Favorite::new).with(Favorite::setClient, SecurityUtils.getUserId().toString()).build());
        return getTableApi(favorites);
    }

    /**
     * 我的收藏列表
     * @param favorite
     * @return
     */
    @GetMapping("")
    public TableDataApi list(Favorite favorite) {
        favorite.setClient(SecurityUtils.getUserId().toString());
        startPageApi();
        List<Favorite> favorites = favoriteService.selectFavoritesHouseInfo(favorite);
        return getTableApi(favorites);
    }
}
